require 'uri'
require 'net/https'
require 'net/https'
require 'json'

module Auth
	CLIENT_ID = ENV['CLIENT_ID']
	CLIENT_SECRET = ENV['CLIENT_SECRET']

	def auth_login
		if session and username = session['username']
			return User.first(:name => username)

		elsif params and params[:code]
			url = URI "https://github.com/login/oauth/access_token?client_id=#{CLIENT_ID}&client_secret=#{CLIENT_SECRET}&code=#{params[:code]}"

			http = Net::HTTP.new(url.host, url.port)
			http.use_ssl = true if url.scheme == 'https'
			http.verify_mode = OpenSSL::SSL::VERIFY_NONE

			resp = http.request_get(url.request_uri, {'Referer' => request.url})

			case resp
			when Net::HTTPSuccess
				resp = Rack::Utils.parse_nested_query(resp.body)
				access_token = resp['access_token']
			when Net::HTTPRedirection
				return nil
			else
				return nil
			end

			url = URI "https://api.github.com/user?access_token=#{access_token}"
			http = Net::HTTP.new(url.host, url.port)
			http.use_ssl = true if url.scheme == 'https'
			http.verify_mode = OpenSSL::SSL::VERIFY_NONE

			resp = http.request_get(url.request_uri, {'Referer' => request.url})
			case resp
			when Net::HTTPSuccess
				resp = JSON.parse(resp.body)
			when Net::HTTPRedirection
				return nil
			else
				return nil
			end

			username = resp['login']
			description = resp['bio']
			user = User.first_or_create(:name => username, :description => description, :user_group_id => UserGroup.first(:name => 'Anonymous').id) if username and username != ""
			session[:username] = user.name if user
			puts session[:username]
			redirect session[:original_url]

		else
			session[:original_url] = request.url
			redirect "https://github.com/login/oauth/authorize?client_id=#{CLIENT_ID}&redirect_uri=#{request.url}"

		end
	end
end
